package de.tum.in.eist.im.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;


import de.tum.in.eist.im.client.domain.User;

/**
 *  Provides register functionality for new users.
 *  Logs user automatically in and creates new chat after registration.
 * 
 * 
 * @author Dennis
 *
 */
public class Register {
		// textboxes
		private PasswordTextBox ptb;
		private  PasswordTextBox ptbConfirm;
		private TextBox tb;
		
		// User
		private User newUser;
		
		//server rpc
		private ChatServiceAsync chatSvc = GWT.create(ChatService.class);
		
		/**
		 *  Constructor calls setContent() method for general functionality management.
		 * 
		 */
		public Register() {
			setContent();
		}
		/**
		 * 
		 * Provides registration content.
		 * Manages screen layout and initializes content widgets.
		 * 
		 * Reacts to button click and keyboard enter-key events.
		 * 
		 */
		public void setContent(){
			//setup login screen
			RootPanel.get("header").clear();
			RootPanel.get("content").clear();
			RootPanel.get("footer").clear();
			// header
		    Label title = new Label();
		    title.setText("Registration");
		    title.setStylePrimaryName("registrationHeader");
		    // body content
		    ptb = new PasswordTextBox();
		    ptb.setStylePrimaryName("regPasswordBox");
		    ptbConfirm = new PasswordTextBox();
		    ptbConfirm.setStylePrimaryName("regPasswordBoxConfirm");
		    tb = new TextBox();
		    tb.setStylePrimaryName("regUsernameBox");
		    FlexTable fb = new FlexTable();
		    Button registerButton = new Button();
		    registerButton.setText("Confirm registration");
		    registerButton.setStylePrimaryName("registrationbutton");
		    fb.setText(0, 0, "Username: ");
		    fb.setWidget(0, 1, tb);
		    fb.setText(1, 0, "Password: ");
		    fb.setWidget(1, 1, ptb);
		    fb.setText(2, 0, "Confirm Password: ");
		    fb.setWidget(2, 1, ptbConfirm);

		    
		    // Add them to the content root panel.
		    VerticalPanel panel = new VerticalPanel();
		    panel.setStylePrimaryName("registrationPanel");
		    panel.add(fb);
		    panel.add(registerButton);
		    RootPanel.get("header").add(title);
		    RootPanel.get("content").add(panel);
		    
		    // Managing events
		    
		    // Listen for register button clicks
		    registerButton.addClickHandler(new ClickHandler() {
		    	public void onClick(ClickEvent event) {
		    		registerNewUser();
		    	}
		    });
		    
		    //keypress enter calls registerNewUser too
		    tb.addKeyPressHandler(new KeyPressHandler() {
		    	public void onKeyPress(KeyPressEvent event) {
		    		if(event.getCharCode() == KeyCodes.KEY_ENTER)
		    		registerNewUser();
		    	}
		    });

		    //keypress enter calls registerNewUser too
		    ptb.addKeyPressHandler(new KeyPressHandler() {
		    	public void onKeyPress(KeyPressEvent event) {
		    		if(event.getCharCode() == KeyCodes.KEY_ENTER)
		    		registerNewUser();
		    	}
		    });
		    
		    //keypress enter calls registerNewUser too
		    ptbConfirm.addKeyPressHandler(new KeyPressHandler() {
		    	public void onKeyPress(KeyPressEvent event) {
		    		if(event.getCharCode() == KeyCodes.KEY_ENTER)
		    			registerNewUser();
		    	}
		    });
		   
		}
		/**
		 *  Registers new user with server. Handles server communication.
		 * 
		 * 
		 */
		public void registerNewUser(){
			Boolean emptyField = false;
			String userName = tb.getText();
			if(userName.isEmpty()) emptyField = true;
			String password = ptb.getText();
			if(password.isEmpty()) emptyField = true;
			String passwordConfirm = ptbConfirm.getText();
			if(passwordConfirm.isEmpty()) emptyField = true;
			if(emptyField) {
				Window.alert("One or more fields are empty." + '\n' + "Please fill out the complete form.");
			} else{
				if(password.equals(passwordConfirm)){
					newUser = new User(userName, password);
					  // Initialize the service proxy.
				    if (chatSvc == null) {
				      chatSvc = GWT.create(ChatService.class);
				    }
				    // Set up the callback object.
				    AsyncCallback<Void> callback = new AsyncCallback<Void>() {
				      public void onFailure(Throwable caught) {
				         Window.alert("Registration failed. \n No Connection to Server.");
				      }

					public void onSuccess(Void result) {
					//do something after registration
						Window.confirm("Registration was successfull.");
						login();
						}
					};
				    // Make the call to the stock price service.
				    chatSvc.registerNewUser(newUser, callback);
				}
				else {
					Window.alert("Passwords do not match!");
				}
			}
		}
		/**
		 * 
		 *  Login the user on the server.
		 *  Creates new Chat after successful login.
		 * 
		 */
		public void login(){
			// Set up the callback object.
		    AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
		      public void onFailure(Throwable caught) {
		         Window.alert("Login failed. \n No Connection to Server.");
		      }
			public void onSuccess(Boolean result) {
			
				// start chat after login
				if(result)
				new Chat(newUser);
				else Window.alert("Authentication failed.");
				
			}
		    };
		    chatSvc.login(newUser, callback);
			
		}
	
}
